﻿using Nest;
using System.Collections.Generic;
using System.Linq;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class ShouldSpecification<T> : ISearchSpecification<ISearchRequest<T>>
        where T : class
    {
        private readonly int _minimumShouldMatch;
        private readonly List<ISearchSpecification<ISearchRequest<T>>> _queries;

        public ShouldSpecification(int minimumShouldMatch = 1)
        {
            _minimumShouldMatch = minimumShouldMatch;
            _queries = new List<ISearchSpecification<ISearchRequest<T>>>();
        }

        public bool HasQuery()
        {
            return _queries.Any();
        }

        public void AddQuery(ISearchSpecification<ISearchRequest<T>> specification)
        {
            _queries.Add(specification);
        }

        public ISearchRequest<T> IsSatisfiedBy()
        {
            return new SearchDescriptor<T>()
                .Query(qq => qq
                    .Bool(b => b
                        .MinimumShouldMatch(_minimumShouldMatch)
                        .Should(
                            _queries.Select(qu => qu
                                .IsSatisfiedBy()
                                .Query
                            ).ToArray()
                        )
                    )
                );
        }
    }
}